//
//  BaseWebViewController.m
//  FeiBiaoApp
//
//  Created by ltl的mac on 16/9/13.
//  Copyright © 2016年 ltl的mac. All rights reserved.
//

#import "BaseWebViewController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "UIView+EWTErrorPage.h"
#import "UIView+EWTPayPage.h"
#import <ShareSDK/ShareSDK.h>
#import <AlipaySDK/AlipaySDK.h>

@interface BaseWebViewController ()<NJKWebViewProgressDelegate,UIGestureRecognizerDelegate>
{
    // 进度条
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}
@end

@implementation BaseWebViewController


-(instancetype)initWithTitle:(NSString *)title url:(NSString *)url
{
    self=[super init];
    if (self) {
        _navTitle=title;
        _url=url;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.delegate=self;
    
    [self addContentView];
    
    [self modeifyNavBar];
    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"ObjC received message from JS: %@", data);
        responseCallback(@"Response for message from ObjC");
    }];
}


-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

-(void)modeifyNavBar
{
    self.navigationItem.title=_navTitle;
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:16],
       
       NSForegroundColorAttributeName:BLACKCOLOR1}];
}

-(void)addContentView
{
    _webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, StatusBar_Height, ScreenSize.width, ScreenSize.height-StatusBar_Height)];
    _webView.backgroundColor=[UIColor whiteColor];
    _webView.scalesPageToFit = YES;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    _webView.delegate=self;
    [self.view addSubview:_webView];
    
    _webView.scrollView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag;
    _webView.opaque=NO;
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    
    CGRect barFrame = CGRectMake(0,
                                 20,
                                 self.view.frame.size.width,
                                 2);
    
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_progressView setProgress:0 animated:YES];
    NSURL* url=[NSURL URLWithString:_url];
    NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    [_webView loadRequest:request];
    [_webView addSubview:_progressView];
    
    
}


#pragma mark - WebviewDelegate
-(void)webViewDidStartLoad:(UIWebView *)webView
{

}


-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSString* title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.navigationItem.title = [title length]>0 ? title:self.navTitle;
   
}


-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    WEAKSELF
    [self.view showErrorPage:@"页面加载失败，请稍后重试" actionHandler:^{
        NSURL* url=[NSURL URLWithString:weakSelf.url];
        NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [weakSelf.webView loadRequest:request];
    }];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 过滤网页广告
    NSString* urlString=[request.URL absoluteString];
    NSRange range=[urlString rangeOfString:@".10010.com"];
    if (range.location!=NSNotFound) {
        return NO;
    }
    
    range=[urlString rangeOfString:@".189.com"];
    if (range.location!=NSNotFound) {
        return NO;
    }
    
    range=[urlString rangeOfString:@".10086.com"];
    if (range.location!=NSNotFound) {
        return NO;
    }
    
//    __weak BaseWebViewController* wself = self;
    NSLog(@"返回的URL==%@",urlString);
//    NSURL *url = [request URL];
//    
////        NSString *urlString  = [url absoluteString];
//    
//        NSArray *typeArray = [urlString componentsSeparatedByString:@"."];
//    
//        NSArray *filenameArray = [urlString componentsSeparatedByString:@"&"];
//    
//        
//    
//        NSString *type = [typeArray lastObject];
//    
//    //查看url的后缀是否是一个可以下载的文件
//    
//        if([type isEqualToString:@"pdf"]||[type isEqualToString:@"docx"]||[type isEqualToString:@"xls"]){
//        
//                //下载到本地（拼本地的地址）
//        
//                NSString *temp = filenameArray[filenameArray.count-2];
//        
//                NSArray *finalFilenameArray = [temp componentsSeparatedByString:@"/"];
//        
//                
//        
//               NSString *fileName = [finalFilenameArray lastObject];
//        
//                //获取下载后文件路径（这里可以根据个人自定义下载的目标地址）
//        
//              // NSString *filePath = [documentDir stringByAppendingPathComponent:fileName];
//        
//        
//        
//                // connection
//        
//                NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//        
//                
//        
//                // 让connection支持多线程，指定代理的工作队列即可
//        
//                // NSURLConnection在运行时，运行循环不负责监听代理的具体执行
//        
//                [connection setDelegateQueue:[[NSOperationQueue alloc] init]];
//        
//        
//        
//                // 3. 启动连接
//        
//                [connection start];
//        
//                
//        
//            }
//
//
//    BOOL isIntercepted = [[AlipaySDK defaultService] payInterceptorWithUrl:urlString fromScheme:@"alipayppp" callback:^(NSDictionary*result) {
//
//        // 处理支付结果
//
//        NSLog(@"返回的的的的的d=%@", result);
//
//        // isProcessUrlPay 代表 支付宝已经处理该URL
//
//        if([result[@"isProcessUrlPay"]boolValue]) {
//
//            // returnUrl 代表 第三方App需要跳转的成功页URL
//
//            NSString* urlStr = result[@"returnUrl"];
//
//            [wself loadWithUrlStr:urlStr];
//
//
//
//        }
//
//    }];
//
//    if(isIntercepted) {
//        return NO;
//    }
//    NSString* reqUrl = request.URL.absoluteString;
//    if ([reqUrl hasPrefix:@"alipays://"] || [reqUrl hasPrefix:@"alipay://"]) {
//        BOOL bSucc = [[UIApplication sharedApplication]openURL:request.URL];
//        //bSucc是否成功调起支付宝
//        if (!bSucc) {
//            NSLog(@"调用失败");
//            return NO;
//        }
//    }
  
    return YES;
}



#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}


-(void)dealloc
{
    _webView.delegate = nil;
    _progressProxy.webViewProxyDelegate = nil;
    _progressProxy.progressDelegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

    - (void)loadWithUrlStr:(NSString*)urlStr
    
    {
        
        if(urlStr.length>0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSURLRequest*webRequest =[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                          cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                      timeoutInterval:10];
                
                [self.webView loadRequest:webRequest];
                
            });
            
        }
        
    }

@end
